<?php
/**
 * Note: 短信服务
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Messages\CaptchaMessage;
use iBrand\Sms\Facade as Sms;
use Illuminate\Support\Facades\Validator;

class SmsService
{
    /**
     * 发送短信验证码
     * @param $mobile
     * @return array
     * @throws ApiException
     * @throws \Illuminate\Validation\ValidationException
     */
    public static function sendVerifyCode($mobile, $source = null): array
    {
        Validator::make([
            'mobile' => $mobile,
            'source' => $source
        ], [
            'mobile' => 'required|cn_mobile',
            'source' => 'nullable'
        ])->validate();

        if (!Sms::canSend($mobile)) throw new ApiException(__('api.sms_request_fast'));

        $codeObject = Sms::getNewCode($mobile);
        $validMinutes = (int) config('ibrand.sms.code.validMinutes', 10);

        $result = false;
        try {
            $result = Sms::send($mobile, new CaptchaMessage($codeObject, $validMinutes, $source));
        } catch (\Exception $e) {}

        if (!$result) throw new ApiException(__('api.sms_request_fail'));

        return [$mobile, $codeObject->code, $codeObject->expireAt];
    }

    /**
     * 检查验证码
     * @param $mobile
     * @param $code
     * @return bool
     * @throws ApiException
     * @throws \Illuminate\Validation\ValidationException
     */
    public static function checkVerifyCode($mobile, $code): bool
    {
        $inputData = [
            'mobile' => $mobile,
            'code' => $code,
        ];
        Validator::make($inputData, [
            'mobile' => 'required|cn_mobile',
            'code' => 'required|min:4|max:6',
        ])->validate();

        if (!Sms::checkCode($mobile, $code)) throw new ApiException(__('api.sms_check_fail'));
        return true;
    }
}
